//已过时，不建议引用，请参考user.html编写新页面

layui.define(['jquery', 'layer', 'element', 'laypage', 'form', 'laytpl'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;

    var laytpl = layui.laytpl;
    var element = layui.element();
    var laypage = layui.laypage;
    var form = layui.form();

    var module_name = 'adp';

    var ADP = function () {
        this.config = {
            formid: 'queryForm',  //查询formid
            onMergeWindowShow: function (form) {

            }

        };
        this.tabledataList = [];

    };
    /**
     * [参数设置 options]
     */
    ADP.prototype.set = function (options) {
        var _this = this;
        $.extend(true, _this.config, options);
        return _this;
    };

    //一些工具方法
    ADP.prototype.post = function (config, callback, mask) {
        var maskid = undefined;
        if (mask) {
            maskid = layer.load();
        }
        $.post({
            url: "../rs/" + config.service + "/" + config.method,
            data: JSON.stringify(config.data || {})


        }).error(function (data) {
            layer.msg(data.responseText);
            if (data.status == 401) {
                parent.window.location.href = "../login.html";
            }
        }).success(function (data) {
            if (data && data.error) {
                // layer.alert(data.error);
                layer.alert(data.error, {
                    skin: 'layui-layer-lan',
                    closeBtn: 0,
                    anim: 4 //动画类型
                });
            } else {

                callback(data);
            }

        }).always(function (data) {
            if (mask) {
                layer.close(maskid);
            }
        });
    };

    //整理一下layui生成的form数据，方便后台接收
    ADP.prototype.wrap = function (obj) {
        var deleteProperty = [];
        //处理类似的表单resources[5].permission为{resources:[{permission:value}...]}
        var re = /^([a-zA-Z0-9]+)\[[0-9]+\]\.([a-zA-Z0-9]+)$/;
        //处理类似的表单resources[5]为{resources:[value...]}
        var re2 = /^([a-zA-Z0-9]+)\[[0-9]+\]$/;
        //处理类似的表单resources.permission为{resources:{permission:value}]}
        var re3 = /^([a-zA-Z0-9]+)\.([a-zA-Z0-9]+)$/;
        var _warp = {};
        for (var key in obj) {
            if (re.test(key)) {

                var keyarr = re.exec(key);
                var target = _warp[keyarr[1]]
                var temp = JSON.parse('{"' + keyarr[2] + '":"value"}');
                temp[keyarr[2]] = obj[key];
                if (target) {
                    target.push(temp);
                } else {
                    _warp[keyarr[1]] = [temp];
                }
                deleteProperty.push(key);
            } else if (re2.test(key)) {
                //TODO:用到再说
            } else if (re3.test(key)) {
                //TODO:用到再说
            }
        }
        $.extend(obj, _warp);
        for (var i = 0; i < deleteProperty.length; i++) {
            delete obj[deleteProperty[i]];
        }
        return obj;
    };

    //用obj给form赋值
    ADP.prototype.fillData = function (obj, $form) {
        var re1 = /^([a-zA-Z0-9]+)$/;
        var re2 = /^([a-zA-Z0-9]+)\[[0-9]+\]\.([a-zA-Z0-9]+)$/;
        var re3 = /^([a-zA-Z0-9]+)\.([a-zA-Z0-9]+)$/;

        $form.find("[name]").each(function () {
            var tagName = $(this)[0].tagName;
            var name = $(this).attr('name');


            // alert(tagName+name);
            if (tagName == 'INPUT') {
                var type = $(this).attr('type');
                if (type == 'radio') {
                    if (re1.test(name)) {
                        $(this).attr('checked', $(this).val() == obj[name]);
                    } else if (re3.test(name)) {
                        var keyarr = re3.exec(name);
                        $(this).attr('checked', $(this).val() == obj[keyarr[1]][keyarr[2]]);
                    }
                } else if (type == 'checkbox') {
                    if (re2.test(name)) {
                        var keyarr = re2.exec(name);
                        var checkboxvalue = $(this).val();
                        var list = obj[keyarr[1]];
                        for (var i = 0; i < list.length; i++) {
                            if (list[i][keyarr[2]] == checkboxvalue) {
                                $(this).attr('checked', true);
                            }
                        }
                    } else if (re1.test(name)) {
                        if (obj[name] == true && $(this).val() == '1') {
                            $(this).attr('checked', true);
                        }
                    }

                } else {
                    if (re1.test(name)) {
                        $(this).val(obj[name]);
                    } else if (re3.test(name)) {
                        var keyarr = re3.exec(name);
                        $(this).val(obj[keyarr[1]][keyarr[2]]);
                    }
                }
            } else if (tagName == 'SELECT' || tagName == 'TEXTAREA') {
                if (re1.test(name)) {
                    $(this).val(obj[name]);
                } else if (re3.test(name)) {
                    var keyarr = re3.exec(name);
                    $(this).val(obj[keyarr[1]][keyarr[2]]);
                }
            }

        });

    };

    //根据id获取表格数据
    ADP.prototype.getRow = function (id) {
        for (var i = 0; i < this.tabledataList.length; i++) {
            if (this.tabledataList[i].id == id) {
                return this.tabledataList[i];
            }
        }
    };

    ADP.prototype.init = function () {
        var _this = this;

        var _config = _this.config;
        _config.pageDivId = "page_box";

        var $form = $("#" + _config.formid);//form
        var $query = $form.find('[lay-filter="adp-query-bth"]');//query button

        $form.next("table").after("<div id='" + _config.pageDivId + "'></div>");
        var $page = $("#" + _config.pageDivId);//page div

        $query.data("pageNumber", 0);

        //画表格
        var darwTable = function (result) {
            laytpl(_config.tablebodytpl).render(result, function (html) {
                $form.next("table").find("tbody").html(html);
            });

            laypage({
                cont: _config.pageDivId,
                curr: result.pageNumber + 1,
                pages: result.total / result.pageNumber,//总页数
                pages: (result.total + result.pageSize - 1) / result.pageSize,//总页数
                groups: 10, //连续显示分页数
                jump: function (obj, first) {
                    var curr = obj.curr;
                    if (!first) { //first一个Boolean类，检测页面是否初始加载。非常有用，可避免无限刷新。
                        // layer.msg('第 ' + obj.curr + ' 页');
//                        layer.alert(curr);
                        $query.data("pageNumber", obj.curr - 1);
                        $query.trigger('click');
                        $query.data("pageNumber", 0);
                    }
                }
            });
        };

        //查询btn绑定处理函数
        form.on("submit(adp-query-bth)", function (data) {
            var elem = data.elem;
            var f = data.form;
            var field = data.field;
            field.pageNumber = $query.data("pageNumber");

            _this.post({service: _config.service, method: "list", data: field}, function (result) {
                _this.tabledataList = result.list;
                darwTable(result);
            }, true);
            return false;
        });

        if (_config.load) {
            $query.trigger('click');
        }
        //-----------merge处理----------------
        var $mergeform = $("#adp-merge-content").find("form");

        var windowid;
        var saveOrUpdate = function () {

            windowid = layer.open({
                type: 1,
                title: arguments.length > 0 ? "修改" : "添加",
                area: ( $("#adp-merge-content").width() + 50) + 'px',//弹出框宽度
                content: $('#adp-merge-content')
            });

            $mergeform.find("input[name='id']").val('');
            $mergeform.find(":checkbox").each(function () {
                $(this).attr("checked", false);
            });
            form.render("checkbox");
            $mergeform.get(0).reset();

            if (arguments.length > 0) {//修改
                var entity = arguments[0];
                // layer.msg(JSON.stringify(arguments[0]));

                _this.fillData(arguments[0], $mergeform);
                form.render("checkbox");
            }
            _config.onMergeWindowShow($mergeform);
        };
        $(".adp-add-btn").click(function () {
            saveOrUpdate();
        });
        $("table").on("click", ".adp-update-btn", function () {
            var id = $(this).data("id");
            saveOrUpdate(_this.getRow(id));
        });
        $("table").on("click", ".adp-delete-btn", function () {
            var id = $(this).data("id");


            layer.confirm("确定要删除吗？", {title: "确认"}, function (index) {
                _this.post({service: _config.service, method: "delete", data: {ids: [id]}}, function (result) {
                    $query.trigger('click');
                    layer.msg("删除成功!");
                }, true);
                layer.close(index);
            });


        });
        $(".adp-delete-all-btn").on("click", function () {
            var ids = [];
            $("td input:checked").each(function (i, e) {
                ids.push(parseInt(e.value));
            });
            if (ids.length == 0) {
                layer.msg("请勾选要删除的数据项!")
                return;
            }

            layer.confirm("确定要删除吗？", {title: "确认"}, function (index) {
                _this.post({service: _config.service, method: "delete", data: {ids: ids}}, function (result) {
                    $query.trigger('click');
                    layer.msg("删除成功!");
                }, true);
                layer.close(index);
            });
        });

        $("th input:checkbox").on("click", function (event) {
            var checked = event.target.checked;
            $("tr input:checkbox").each(function (i, e) {
                e.checked = checked;
            });
        });

        form.on("submit(adp-merge-btn)", function (data) {
            var field = data.field;
            //checkbox处理,废弃，暂时保留一段时间
            // $(data.form).find('input[type="checkbox"]:checked').each(function () {
            //     var chk = field[$(this).attr("name")];
            //     if ($.isArray(chk)) {
            //         chk.push($(this).val());
            //     } else {
            //         field[$(this).attr("name")] = [$(this).val()];
            //     }
            //
            // });
            _this.post({service: _config.service, method: "merge", data: _this.wrap(field)}, function (result) {
                layer.close(windowid);
                $query.trigger('click');
            }, true);
            return false;
        });
        return _this;
    };

    var adp = new ADP();
    exports(module_name, function (options) {
        return adp.set(options).init();

    });

});
